import { reqGetCode, reqUserRegister, reqUserLogin,reqUserInfo ,reqLogout} from "@/api"
import {setToken,getToken,removeToken} from '@/utils/token'

const actions = {
    //验证码
    async getCode({ commit }, phone) {
        let result = await reqGetCode(phone)
        if (result.code == 200) {
            commit("GETCODE", result.data)
            return 'ok'
        } else {
            return Promise.reject(new Error("faile"))
        }
    },
    //用户注册
    async userRegister({ commit }, user) {
        let result = await reqUserRegister(user)
        if (result.code == 200) {
            return 'ok'
        } else {
            return Promise.reject(new Error("faile"))
        }
    },
    //用户登录
    async userLogin({ commit }, data) {
        let result = await reqUserLogin(data)
        if (result.code == 200) {
            commit("GETTOKEN", result.data)
            //本地存储token
            setToken(result.data.token)
            return 'ok'
        } else {
            return Promise.reject(new Error("faile"))
        }
    },
    //获取用户信息
    async userInfo({commit}){
        let result =await reqUserInfo()
        if (result.code == 200) {
            commit("GETUSERINFO", result.data)
            return 'ok'
        } else {
            // return Promise.reject(new Error("faile"))
        }
    },
    //退出登录
   async userLogout({commit}){
        let result = await reqLogout()
        if(result.code==200){
            //清空数据
            commit("CLEAR")
            return 'ok'
        }else {
            return Promise.reject(new Error("faile"))
        }
    }
}
const mutations = {
    GETCODE(state, code) {
        state.code = code
    },
    GETTOKEN(state, data) {
        state.token = data.token
        state.name = data.name
    },
    GETUSERINFO(state,userInfo){
        state.userInfo=userInfo || {}
    },
    CLEAR(state){
        state.token = ''
        state.user ={}
        removeToken()
    }
}
const state = {
    code: '',
    token: getToken(),
    name: '',
    userInfo:'',
}
const getters = {

}

export default {
    namespaced: true,
    actions,
    mutations,
    state,
    getters
}